//
//  TableView.m
//  itv
//
//  Created by Zhang Yinghui on 9/28/11.
//  Copyright 2011 LavaTech. All rights reserved.
//

#import "BKTableView.h"
#import "BKKit.h"
#import "BKHttpRequestManager.h"
#import "Theme.h"
#import "NSString+x.h"
#import "UIImage+x.h"
#import "BKLineView.h"
#import "BKScrollView.h"
#import "UILabel+x.h"

@implementation BKTableView

- (void)setup{
    if (self.style != UITableViewStyleGrouped) {
        if (_topLine && [_topLine superview]) {
            [_topLine removeFromSuperview];
        }
        ////
        _topLine = [[BKLineView alloc] initWithFrame:CGRectMake(0, -2, self.frame.size.width, 2)];
        _topLine.lineWidth = 0.5;
        _topLine.autoresizingMask = UIViewAutoresizingFlexibleWidth;
        [_topLine setColors:[NSArray arrayWithObjects:THEME_LINE_TOP_COLOR, THEME_LINE_BOTTOM_COLOR,nil]];
        //[self addSubview:_topLine];
    }
    self.backgroundColor = [UIColor clearColor];
    [self setScrollsToTop:YES];
}
- (id) initWithFrame:(CGRect)frame style:(UITableViewStyle)style{
	self = [super initWithFrame:frame style:style];
	if (self) {
        self.separatorStyle = UITableViewCellSeparatorStyleNone;
        self.backgroundColor = [UIColor clearColor];
        self.delegate = self;
        self.dataSource = self;
        [self setup];
    }
	return self;
}
- (id) initWithFrame:(CGRect)frame{
	self = [super initWithFrame:frame style:UITableViewStylePlain];
	if (self) {
        self.separatorStyle = UITableViewCellSeparatorStyleNone;
        self.backgroundColor = [UIColor clearColor];
        self.delegate = self;
        self.dataSource = self;
        [self setup];
		
	}
	return self;
}
-(void)awakeFromNib{
    [super awakeFromNib];
    [self setup];
}
- (void)reloadData{
    [super reloadData];
}

- (void)addFormRow:(int)fromRow toRow:(int)toRow forSection:(int)section{
    NSMutableArray *indexPaths = [NSMutableArray array];
    for (int i = fromRow; i < toRow; i++) {
        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:i inSection:section];
        [indexPaths addObject:indexPath];
    }
    [self insertRowsAtIndexPaths:indexPaths withRowAnimation:UITableViewRowAnimationNone];
}
- (NSString *)imageCacheForIndexPath:(NSIndexPath *)indexPath{
	if (!_imgCache) {
		return nil;
	}
	return [_imgCache objectForKey:indexPath];
}
- (NSString *)imageCacheForUrl:(NSString *)url{
	if (!_imgCache) {
		return nil;
	}
	return [_imgCache objectForKey:[url md5]];
}
- (void)cacheImage:(NSString *)imgLocalPath forIndexPath:(NSIndexPath *)indexPath{
	if (!_imgCache) {
		_imgCache = [NSMutableDictionary dictionaryWithCapacity:[self numberOfRowsInSection:0]] ;
	}
	[_imgCache setObject:imgLocalPath forKey:indexPath];
}
- (void)cacheImage:(NSString *)imgLocalPath forUrl:(NSString *)url{
	if (!_imgCache) {
		_imgCache = [NSMutableDictionary dictionaryWithCapacity:[self numberOfRowsInSection:0]] ;
	}
	[_imgCache setObject:imgLocalPath forKey:[url md5]];
}
- (void) loadImage:(NSString *)imgURL forIndexPath:(NSIndexPath *)indexPath{
	if (!imgURL) {
		return;
	}
	if (!_queue) {
		_queue = [[NSOperationQueue alloc] init];
	}
    NSString *url = [imgURL stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet letterCharacterSet]];
    DLOG(@"loadImg:%@",url);
    BKHttpRequestManager * manager = [BKHttpRequestManager defaultManager];
    [manager download:url
             progress:nil
              success:^(id  _Nonnull task, id  _Nullable fp) {
              }
              failure:^(id  _Nullable task, id  _Nullable fp, NSError * _Nonnull error) {
                  
              }];
    
}
#pragma GCC diagnostic ignored "-Wundeclared-selector"
- (void)setImagePath:(NSString *)fp forURL:(NSURL *)url forIndexPath:(NSIndexPath *)indexPath{
    if (self.delegate && [self.delegate respondsToSelector:@selector(tableView:didLoadedImageAtPath:forIndexPath:)]) {
        [(id)self.delegate tableView:self didLoadedImageAtPath:fp forIndexPath:indexPath];
        return;
    }
    if (indexPath && [self cellForRowAtIndexPath:indexPath]) {
        UITableViewCell *cell = [self cellForRowAtIndexPath:indexPath];
        if ([cell respondsToSelector:@selector(setImgageFilePath:)]) {
            [cell performSelector:@selector(setImgageFilePath:) withObject:fp];
        }else if([cell respondsToSelector:@selector(setImage:)]){
            [cell performSelector:@selector(setImage:) withObject:[UIImage imageWithContentsOfFile:fp]];
        }
        if (self.delegate && [self.delegate respondsToSelector:@selector(tableView:cacheImagePath:forIndexPath:)] ) {
            [(id)self.delegate tableView:self cacheImagePath:fp forIndexPath:indexPath];
        }else{
            [self cacheImage:fp forUrl:[url absoluteString]];
        }
    }
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 0;
}
- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    return nil;
}

- (void)dealloc {
	if (_queue && [_queue operationCount]>0) {
		[_queue cancelAllOperations];
	}
}
@end

@interface BKTableViewSectionView()
@property (nonatomic, retain) UIImageView *leftImageView;
@property (nonatomic, retain) UIImageView *rightImageView;
@property (nonatomic, assign) id target;
@property (nonatomic, assign) SEL action;
@end
@implementation BKTableViewSectionView
- (id)initWithFrame:(CGRect)frame{
	if (self = [super initWithFrame:frame]) {
		self.separatorLineStyle = SeparatorLineStyleTop | SeparatorLineStyleBottom;
        
        _titleLabel = createLabel(CGRectZero, THEME_TABLE_SECTION_FONT, [UIColor clearColor], THEME_TABLE_SECTION_COLOR, nil, CGSizeZero, NSTextAlignmentLeft, 1, 0) ;
        _rightLabel = createLabel(CGRectZero, THEME_TABLE_SECTION_FONT, [UIColor clearColor], THEME_TABLE_SECTION_COLOR, nil, CGSizeZero, NSTextAlignmentRight, 1, 0) ;
        [self addSubview:_titleLabel];
        [self addSubview:_rightLabel];
        
        //self.backgroundColor = gTableSectionBgColor;
        UITapGestureRecognizer *tap = /*AUTORELEASE*/([[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapEvent:)]);
        [self addGestureRecognizer:tap];
        
	}
	return self;
}
- (void)layoutSubviews{
    [super layoutSubviews];
    float padding = 10, w = self.bounds.size.width, h = self.bounds.size.height;
    CGRect labelFrame = CGRectInset(self.bounds, padding, (h - [THEME_TABLE_SECTION_FONT pointSize]-4)/2);
    if (self.leftImageView) {
        CGRect r = self.leftImageView.frame;
        r.origin = CGPointMake( padding, (h-self.leftImageView.bounds.size.height)/2);
        self.leftImageView.frame = r;
        labelFrame.origin.x += r.size.width+padding/2;
        labelFrame.size.width -= r.size.width+padding;
    }
    if (self.rightImageView) {
        CGRect r = self.rightImageView.frame;
        r.origin = CGPointMake( w - padding-r.size.width, (h-self.rightImageView.bounds.size.height)/2);
        self.rightImageView.frame = r;
        labelFrame.size.width -= r.size.width+padding/2;
    }
    self.titleLabel.frame = labelFrame;
    if (self.rightTitle)
        self.rightLabel.frame = labelFrame;
    if (self.rightView) {
        CGRect rightViewFrame = self.rightView.bounds;
        rightViewFrame.origin.x = labelFrame.origin.x + labelFrame.size.width - rightViewFrame.size.width;
        rightViewFrame.origin.y = (h-rightViewFrame.size.height)/2;
        self.rightView.frame = rightViewFrame;
    }
}
- (void)setLeftImage:(UIImage *)leftImage{
    ////
    _leftImage = leftImage ;
    if (!_leftImageView) {
        _leftImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, leftImage.size.width, MIN(leftImage.size.height, self.bounds.size.height*0.7))];
        [self addSubview:_leftImageView];
    }
    
    __weak __typeof__(leftImage) weakLeftImage = leftImage;
    __weak __typeof(self)weakSelf = self;
    [UIView animateWithDuration:0.2
                     animations:^{
                         __typeof__(weakLeftImage) strongLeftImage = weakLeftImage;
                         __strong __typeof__(weakSelf) strongSelf = weakSelf;
                         strongSelf.leftImageView.image = strongLeftImage;
                     }
                     completion:^(BOOL finished) {
                         [self setNeedsLayout];
                     }];
    [self setNeedsLayout];
}
- (void)setRightImage:(UIImage *)rightImage{
    ////
    _rightImage = rightImage;
    if (!_rightImageView) {
        _rightImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, rightImage.size.width, MIN(rightImage.size.height, self.bounds.size.height*0.7))];
        [self addSubview:_rightImageView];
    }
    _rightImageView.image = rightImage;
    [self setNeedsLayout];
}
- (void)setTitle:(NSString *)title{
    ////
    _title = title;
    _titleLabel.text = title;
}
- (void)setRightTitle:(NSString *)rightTitle{
    ////
    _rightTitle = rightTitle;
    _rightLabel.text = rightTitle;
}
- (void) setRightView:(UIView *)rightView{
    if (_rightView) {
        [_rightView removeFromSuperview];
        ////
    }
    _rightView = rightView;
    [self addSubview:_rightView];
    [self setNeedsLayout];
}

- (void)addTarget:(id)target action:(SEL)action{
    self.target = target;
    self.action = action;
}
- (void)tapEvent:(id)sender{
    if (self.target && self.action) {
//        [self.target performSelector:self.action withObject:self];
        IMP imp = [self.target methodForSelector:self.action];
        void (*func)(id, SEL, NSObject *) = (void *)imp;
        func(self.target, self.action, self);
    }
}
- (void)dealloc{
    ////
    ////
    ////
    ////
    ////
    ////
    ////
    ////
    //[super dealloc];
}
@end

@implementation BKTableViewCellBackground
- (void)setup{
    self.separatorLineStyle = SeparatorLineStyleBottom;
    self.topLineColor = THEME_LINE_TOP_COLOR;
    self.bottomLineColor = THEME_LINE_BOTTOM_COLOR;
}
- (id)initWithFrame:(CGRect)frame{
	
	if (self = [super initWithFrame:frame]) {
        [self setup];
        self.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
        [self setBackgroundColor:[UIColor clearColor]];
	}
	return self;
}
- (id)initWithCoder:(NSCoder *)aDecoder{
	if (self = [super initWithCoder:aDecoder]) {
        [self setup];
    }
	return self;
}
- (void)awakeFromNib{
    [super awakeFromNib];
    self.separatorLineStyle = [self tag];
}
- (void)setFrame:(CGRect)frame{
	[super setFrame:frame];
	[self setNeedsDisplay];
}
- (void)willMoveToSuperview:(UIView *)newSuperview{
    [super willMoveToSuperview: newSuperview];
    [self setNeedsDisplay];
}
- (void)drawLine:(CGPoint)p1 toPoint:(CGPoint)p2 color:(UIColor *)color inContext:(CGContextRef)ctx{
	CGContextMoveToPoint(ctx, p1.x,p1.y);
	CGContextAddLineToPoint(ctx, p2.x,p2.y);	
	CGContextSetStrokeColorWithColor(ctx, color.CGColor);
	CGContextDrawPath(ctx, kCGPathStroke);
}
- (void)setTopLineColor:(UIColor *)topLineColor bottomLineColor:(UIColor *)bottomLineColor{
    ////
    ////
    _topLineColor = topLineColor;
    _bottomLineColor = bottomLineColor;
    [self setNeedsDisplay];
}
- (void)setBackgroundImage:(UIImage *)backgroundImage{
    self.backgroundColor = [UIColor clearColor];
    ////
    _backgroundImage = backgroundImage;
    [self setNeedsDisplay];
}
- (void) drawRect:(CGRect)rect{
    if (self.backgroundImage) {
        [self.backgroundImage drawInRect:rect];
    }
    if (self.separatorLineStyle == SeparatorLineStyleNone) {
        return;
    }
	float lineWidth = 0.5;
    CGContextRef ctx = UIGraphicsGetCurrentContext();
    CGContextSaveGState(ctx);
	CGContextSetShouldAntialias(ctx,false);
	CGContextSetLineWidth(ctx, lineWidth);
	CGPoint p1,p2;
	if (_separatorLineStyle & SeparatorLineStyleTop) {
		
		p1 = CGPointMake(rect.origin.x,rect.origin.y + lineWidth);	
		p2 = CGPointMake(rect.size.width,rect.origin.y+lineWidth);					 
		[self drawLine:p1 toPoint:p2 color:_topLineColor inContext:ctx];							 
		
		p1.y += lineWidth;
		p2.y += lineWidth;	
		[self drawLine:p1 toPoint:p2 color:_bottomLineColor inContext:ctx];
	}
	if (_separatorLineStyle & SeparatorLineStyleBottom) {
		p1 = CGPointMake(rect.origin.x,rect.origin.y+rect.size.height-2*lineWidth);	
		p2 = CGPointMake(rect.size.width,rect.origin.y+rect.size.height-2*lineWidth);					 
		[self drawLine:p1 toPoint:p2 color:_topLineColor inContext:ctx];							 
		
		p1 = CGPointMake(rect.origin.x,rect.origin.y+rect.size.height-lineWidth);
		p2 = CGPointMake(rect.size.width,rect.origin.y+rect.size.height-lineWidth);	
		[self drawLine:p1 toPoint:p2 color:_bottomLineColor inContext:ctx];
	}
    CGContextRestoreGState(ctx);
}
- (void)dealloc{
    ////
    ////
    ////
    //[super dealloc];
}

@end


